package org.icec.sms.service;

import java.util.List;

import org.icec.sms.model.SmsRecord;
import org.icec.sms.support.AliSmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class SmsService {
	@Autowired
	private AliSmsService aliSmsService;
	@Autowired
	private SmsRecordService smsRecordService;
	/**
	 * 扫描短信表，发送到阿里大宇
	 */
	@Transactional
	public void sendSmsToAliyun() {
		log.info("短信发送开始");
		List<SmsRecord> list = smsRecordService.getRecordByState("");
		for(SmsRecord record : list) {
			SendSmsRequest request = new SendSmsRequest();
			request.setPhoneNumbers(record.getPhone());
			request.setTemplateCode(record.getTemplateCode());
			request.setTemplateParam(record.getParam());
			request.setOutId(record.getId()+"");
			String code="";
			try {
				SendSmsResponse response = aliSmsService.sendSms(request);
				code=response.getCode();
				smsRecordService.sendOk(record.getId(), code);
			} catch (ClientException e) {
				 log.error("发送短信异常",e);
			}
		}
		log.info("短信发送完成");
	}
}
